package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 发布动态
     * @param movement
     */
    @Override
    public String publish(Movement movement) {
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //已抽取
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());

        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();
    }

    /**
     * 查看我的动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult all(Long userId, Integer page, Integer pagesize) {
        //补充条件状态码为1的才查出来
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, 0L, movements);
    }

    /**
     * 好友动态查询
     * @param friendId = userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> movements(Long friendId, Integer page, Integer pagesize) {
        //1.构造条件对象查询好友时间线表
        //把传过来的当前登录id等于时间线表中的所有好友id做匹配
        Criteria criteria = Criteria.where("friendId").in(friendId).and("state").is(1);
        Query query = Query.query(criteria).skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2.从好友时间线表集合中提取所有发布动态人id 集合
        List<ObjectId> movementId = CollUtil.getFieldValues(timeLines, "movementId", ObjectId.class);
        //3.根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(movementId));
        return mongoTemplate.find(movementQuery, Movement.class);
    }

    /**
     * 随机获取动态数据
     * @param counts
     * @return
     */
    @Override
    public List<Movement> random(Integer counts) {
        //构造条件  构造10条动态
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(counts));
        //使用mongoTemplate生成返回值为Movement的集合
        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation, Movement.class);
        return movements.getMappedResults();
    }

    /**
     * 查询动态数据 根据pId查询
     * @param longs
     * @return
     */
    @Override
    public List<Movement> findByPids(List<Long> longs) {
        Query query = Query.query(Criteria.where("pId").in(longs).and("state").is(1));
        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * 根据id查询单条动态
     * @param movementId
     * @return
     */
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    /**
     * 查询动态列表
     * @param page
     * @param pagesize
     * @param uid 用户id
     * @param skr 动态状态
     * @return
     */
    @Override
    public PageResult messages(Integer page, Integer pagesize, Long uid, Integer skr) {
        Query query = new Query();
        //1.构造条件查询
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (skr != null) {
            query.addCriteria(Criteria.where("state").is(skr));
        }
        //2.获取数量
        long count = mongoTemplate.count(query, Movement.class);
        //3.进行分页和排序
        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        //4.获取动态集合
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        //5.构造返回
        return new PageResult(page, pagesize, count, list);
    }

    /**
     * 修改动态状态
     * @param movementId
     * @param state
     */
    @Override
    public void update(String movementId, int state) {
        Query query = Query.query(Criteria.where("id").is(movementId));
        Update update = new Update().set("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }
}
